package ru.papergames.web.controllers;

import ru.papergames.common.form.PcPlayerForm;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Alexander Troshanin
 */
public abstract class AuthorizedController extends AbstractController {

    @Override
    public boolean checkAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        PcPlayerForm player = getPcPlayerForm(request);
        if (player == null) {
            request.setAttribute("needToLogon", true);
            sendFailedResult(request, response);
            return false;
        }

        if (player.isDisconnectedToBattleServer()) {
            request.setAttribute("needToConnectToBattleServer", true);
            sendFailedResult(request, response);
            return false;
        }

        if (player.isWaitingForGettingConnected()) {
            request.setAttribute("needToWaitForGettingConnected", true);
            sendFailedResult(request, response);
            return false;
        }
        return true;
    }

    private void sendFailedResult(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/papergames/checkAuthFailed.jsp");
        if (dispatcher != null) {
            dispatcher.forward(request, response);
        }
    }

}
